package com.lonely.deliver.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.enums.CommonStatus;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.deliver.domain.entity.SysPdaScan;
import com.lonely.deliver.mapper.SysPdaScanMapper;
import com.lonely.deliver.service.IPdaScanService;
import com.lonely.order.domain.dto.order.SkcStickerQrCodeDTO;
import com.lonely.order.domain.vo.order.OrderDetailVO;
import com.lonely.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author : 黄志标
 * @date: 2025/9/16 15:41
 * @description: pda扫描服务实现类
 */
@Service
public class PdaScanServiceImpl extends ServiceImpl<SysPdaScanMapper, SysPdaScan> implements IPdaScanService {

    @Autowired
    private IOrderService orderService;

    /**
     * 扫码录数
     *
     * @param skcStickerQrCodeDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scanCodeRecordNum(SkcStickerQrCodeDTO skcStickerQrCodeDTO) {

        // 根据订单号查询对应的信息
        OrderDetailVO orderDetail = this.orderService.getOrderDetail(Convert.toLong(skcStickerQrCodeDTO.getProduceOrderId()));

        // 获取当前尺码是否扫描过
        SysPdaScan pdaScan = super.getOne(new LambdaQueryWrapper<SysPdaScan>()
                .eq(SysPdaScan::getProduceOrderId, skcStickerQrCodeDTO.getProduceOrderId())
                .eq(SysPdaScan::getSkc, orderDetail.getSku())
                .eq(SysPdaScan::getSizeName, skcStickerQrCodeDTO.getSizeName())
                .eq(SysPdaScan::getStatus, CommonStatus.ENABLE.code)
        );

        if (pdaScan == null) {
            // 为扫描过，则创建数据入库
            SysPdaScan newPdaScan = new SysPdaScan();
            newPdaScan.setFactoryId(SecurityUtils.getFactoryId());
            newPdaScan.setProduceOrderId(skcStickerQrCodeDTO.getProduceOrderId());
            newPdaScan.setSkc(orderDetail.getSku());
            newPdaScan.setSizeName(skcStickerQrCodeDTO.getSizeName());
            newPdaScan.setSizeQuantity(1);
            newPdaScan.setStatus(CommonStatus.ENABLE.code);
            newPdaScan.setCreateBy(SecurityUtils.getUserId());
            newPdaScan.setUpdateBy(SecurityUtils.getUserId());
            super.save(newPdaScan);
            return;
        }

        // 已存在数据，则更新尺码数量
        pdaScan.setSizeQuantity(pdaScan.getSizeQuantity() + 1);
        pdaScan.setUpdateBy(SecurityUtils.getUserId());
        super.updateById(pdaScan);

    }
}
